<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/*
 * 写日志
 */
function write_log($message, $filename = 'api')
{
    $filepath = __DIR__ . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . $filename . '.log';
    if (!file_exists($filepath)) {
        $newfile = TRUE;
    }
    if (!$fp = @fopen($filepath, 'ab')) {
        return FALSE;
    }
    $message = $message . "\n";

    flock($fp, LOCK_EX);
    for ($written = 0, $length = strlen($message); $written < $length; $written += $result) {
        if (($result = fwrite($fp, substr($message, $written))) === FALSE) {
            break;
        }
    }
    flock($fp, LOCK_UN);

    fclose($fp);
    if (isset($newfile) && $newfile === TRUE) {
        chmod($filepath, 0644);
    }
    return is_int($result);
}

/*
 * 写日志-丰富message内容
 */
function log_message($message, $filename, $type)
{
    $request = \think\Request::instance();
    $data = [
        'message' => $message, // 信息
        'ip_address' => $request->ip(), // IP地址
        'url' => $request->url(), //URL地址
        'user_agent' => stripslashes(@$_SERVER['HTTP_USER_AGENT']), // 浏览器信息
        'created_at' => date('c'), // 时间
    ];
    write_log(json_encode($data), $filename . '_' . $type);
}

/**
 * 统一返回正确json信息
 * return json_info()
 */
function json_info($message, $state = 200)
{
    log_message($message, 'output', 'log');
    $data = [
        'message' => $message
    ];
    return json($data, $state);
}


/**
 * 统一返回错误json信息
 * return json_info()
 */
function json_error($message, $error_code, $state = 200)
{
    $request = \think\Request::instance();
    $result = [
        'message' => $message,
        'error_code' => $error_code,
        'request_url' => $request->url()
    ];
    log_message($message, 'output', 'log');
    return json($message, $state);
}



// TODO
// 浏览器判断


